<template>
  <div class="user-list">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>用户列表</span>
          <el-button 
            v-if="userStore.isSuperAdmin" 
            type="primary" 
            @click="handleAdd"
          >
            <el-icon><Plus /></el-icon>
            添加用户
          </el-button>
        </div>
      </template>

      <el-table
        v-loading="loading"
        :data="userList"
        style="width: 100%"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="username" label="用户名" />
        <el-table-column prop="role" label="角色">
          <template #default="{ row }">
            <el-tag :type="getRoleType(row.role)">
              {{ getRoleText(row.role) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="lastLoginTime" label="最后登录时间">
          <template #default="{ row }">
            {{ formatDate(row.lastLoginTime) || '未登录' }}
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间">
          <template #default="{ row }">
            {{ formatDate(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" v-if="userStore.isSuperAdmin">
          <template #default="{ row }">
            <el-button-group>
              <el-button
                type="primary"
                size="small"
                @click="handleEdit(row)"
              >
                编辑
              </el-button>
              <el-button
                type="danger"
                size="small"
                @click="handleDelete(row)"
                :disabled="row.id === userStore.userId"
              >
                删除
              </el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @update:current-page="handleCurrentChange"
          @update:page-size="handleSizeChange"
        />
      </div>
    </el-card>

    <!-- 用户表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '添加用户' : '编辑用户'"
      width="500px"
    >
      <el-form
        ref="userFormRef"
        :model="userForm"
        :rules="userRules"
        label-width="80px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userForm.username" />
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="dialogType === 'add'">
          <el-input v-model="userForm.password" type="password" />
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select v-model="userForm.role" style="width: 100%">
            <el-option label="超级管理员" value="SUPER_ADMIN" v-if="userStore.isSuperAdmin" />
            <el-option label="管理员" value="ADMIN" />
            <el-option label="普通用户" value="USER" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue'
import { useUserStore } from '@/store/modules/user'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'

const userStore = useUserStore()
const router = useRouter()
const loading = ref(false)
const dialogVisible = ref(false)
const dialogType = ref('add')
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const userList = ref([])
const userFormRef = ref()

const userForm = reactive({
  id: null,
  username: '',
  password: '',
  role: 'USER'
})

const userRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
  ],
  role: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ]
}

// 检查用户权限
const checkPermission = () => {
  if (userStore.isUser) {
    ElMessage.warning('您没有权限访问此页面')
    router.push('/dashboard')
    return false
  }
  return true
}

const getRoleType = (role) => {
  const map = {
    'SUPER_ADMIN': 'danger',
    'ADMIN': 'warning',
    'USER': 'info'
  }
  return map[role] || 'info'
}

const getRoleText = (role) => {
  const map = {
    'SUPER_ADMIN': '超级管理员',
    'ADMIN': '管理员',
    'USER': '普通用户'
  }
  return map[role] || role
}

const fetchUsers = async () => {
  // 检查权限
  if (!checkPermission()) return
  
  try {
    loading.value = true
    const res = await userStore.getUsers({
      page: currentPage.value,
      pageSize: pageSize.value
    })
    console.log('用户列表数据:', {
      response: res,
      users: userStore.users,
      total: userStore.total
    })
    
    // 对用户列表进行排序，确保按ID从小到大排序
    const allUsers = [...userStore.users].sort((a, b) => {
      // 确保提取正确的ID字段并转为数字
      let idA = a.id !== undefined ? Number(a.id) : 0;
      let idB = b.id !== undefined ? Number(b.id) : 0;
      
      // 确保是数字类型
      idA = isNaN(idA) ? 0 : idA;
      idB = isNaN(idB) ? 0 : idB;
      
      return idA - idB; // 升序排列
    });
    
    console.log('再次确认排序后的用户ID列表:', allUsers.map(u => u.id).join(', '));
    
    // 记录一下 store 中的总数
    console.log('Store中的用户总数:', userStore.total)
    
    // 设置总数
    total.value = userStore.total
    
    // 判断是否需要在前端处理分页
    const needsClientPagination = allUsers.length > pageSize.value;
    
    if (needsClientPagination) {
      console.log('检测到需要前端分页处理，总数据量:', allUsers.length);
      
      // 计算当前页应该显示的数据范围
      const startIndex = (currentPage.value - 1) * pageSize.value;
      const endIndex = Math.min(startIndex + pageSize.value, allUsers.length);
      
      // 从全部数据中截取当前页数据
      userList.value = allUsers.slice(startIndex, endIndex);
      
      console.log(`前端分页: 第${currentPage.value}页，起始索引:${startIndex}，结束索引:${endIndex}`);
      console.log('当前页用户ID:', userList.value.map(u => u.id).join(', '));
      
      // 设置正确的总数
      total.value = allUsers.length;
    } else {
      // 如果数据量较小或后端已处理分页，直接使用数据
      userList.value = allUsers;
      
      // 如果总数小于等于当前显示的数据数量，但明显超过了页大小，则强制设置一个更大的总数
      if (total.value <= userList.value.length && userList.value.length > pageSize.value) {
        total.value = userList.value.length + pageSize.value
        console.log('调整后的用户总数:', total.value)
      }
    }
    
    // 如果仍然只有一页，但有数据，至少显示两页
    if (total.value <= pageSize.value && userList.value.length === pageSize.value) {
      total.value = pageSize.value + 1
      console.log('确保至少有两页的总数:', total.value)
    }
    
    // 最后检查一下当前页的排序是否正确
    const currentPageIds = userList.value.map(u => Number(u.id));
    console.log('当前页最终显示的用户ID:', currentPageIds.join(', '));
    
    // 验证排序是否正确
    const isSorted = currentPageIds.every((id, i) => i === 0 || id > currentPageIds[i - 1]);
    console.log('当前页用户ID是否正确升序排列:', isSorted);
    
    if (!isSorted) {
      console.warn('当前页用户排序异常，手动再次排序');
      userList.value.sort((a, b) => {
        let idA = Number(a.id) || 0;
        let idB = Number(b.id) || 0;
        return idA - idB;
      });
      console.log('重新排序后的用户ID:', userList.value.map(u => u.id).join(', '));
    }
  } catch (error) {
    console.error('获取用户列表失败:', error)
    ElMessage.error('获取用户列表失败: ' + (error.message || '未知错误'))
  } finally {
    loading.value = false
  }
}

const handleSizeChange = (val) => {
  pageSize.value = val
  fetchUsers()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchUsers()
}

const resetForm = () => {
  userForm.id = null
  userForm.username = ''
  userForm.password = ''
  userForm.role = 'USER'
  if (userFormRef.value) {
    userFormRef.value.resetFields()
  }
}

const handleAdd = () => {
  // 检查权限
  if (!userStore.isSuperAdmin) {
    ElMessage.warning('您没有权限添加用户')
    return
  }
  
  dialogType.value = 'add'
  resetForm()
  dialogVisible.value = true
}

const handleEdit = (row) => {
  // 检查权限
  if (!userStore.isSuperAdmin) {
    ElMessage.warning('您没有权限编辑用户')
    return
  }
  
  dialogType.value = 'edit'
  Object.assign(userForm, row)
  dialogVisible.value = true
}

const handleDelete = (row) => {
  // 检查权限
  if (!userStore.isSuperAdmin) {
    ElMessage.warning('您没有权限删除用户')
    return
  }
  
  // 禁止删除自己
  if (row.id === userStore.userId) {
    ElMessage.warning('不能删除当前登录的用户')
    return
  }
  
  ElMessageBox.confirm(
    '确定要删除该用户吗？',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await userStore.deleteUser(row.id)
      ElMessage.success('删除成功')
      fetchUsers()
    } catch (error) {
      ElMessage.error('删除失败')
    }
  })
}

const handleSubmit = async () => {
  // 检查权限
  if (!userStore.isSuperAdmin) {
    ElMessage.warning('您没有权限执行此操作')
    return
  }
  
  if (!userFormRef.value) return
  
  try {
    await userFormRef.value.validate()
    if (dialogType.value === 'add') {
      await userStore.createUser(userForm)
      ElMessage.success('添加成功')
    } else {
      await userStore.updateUser(userForm)
      ElMessage.success('更新成功')
    }
    dialogVisible.value = false
    fetchUsers()
  } catch (error) {
    if (error.message) {
      ElMessage.error(error.message)
    }
  }
}

const formatDate = (date) => {
  if (!date) return ''
  return new Date(date).toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

// 监听 store 中的用户数据变化
watch(() => userStore.users, (newUsers) => {
  console.log('用户数据更新:', newUsers)
  userList.value = newUsers
}, { deep: true })

// 监听表格数据变化
watch(() => userList.value, (newList) => {
  console.log('表格数据更新:', newList)
}, { deep: true })

onMounted(() => {
  checkPermission() && fetchUsers()
})
</script>

<style lang="scss" scoped>
.user-list {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style> 